package bblvolume

import (
	"code.google.com/p/go-uuid/uuid"
	"logger"
	"math/rand"
	"path/filepath"
	"time"
)

var log *logger.Logger // = logger.NewLogger("stdout", "[volume] ", "info")

func UUID() string {
	return uuid.NewUUID().String()
}

func Rand() int {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	return r.Intn(100000000)
}

func Timestamp() uint64 {
	return uint64(time.Now().Unix())
}

func Sleep(millisecond int) {
	time.Sleep(time.Duration(millisecond) * time.Millisecond)
}

func Start(conf string) (err error) {
	if err = init_config(conf); err != nil {
		return err
	}
	if err = init_log(); err != nil {
		return err
	}
	if err := init_volume_server(); err != nil {
		return err
	}
	for _, server := range servers {
		go server.Serve()
	}

	return nil
}

func Stop() {
	for _, server := range servers {
		go server.Stop()
	}
}

func init_log() error {
	logg, err := logger.NewLogger(server_conf.LogFile, "[volume] ", server_conf.LogLevel)
	if err != nil {
		return err
	}
	log = logg
	return nil
}

var servers []*VolumeServer

func init_volume_server() error {
	servers = make([]*VolumeServer, 0)
	for _, vol := range server_conf.Volumes {
		server := new(VolumeServer)
		server.UUID = vol.UUID
		server.Name = vol.Name
		server.Export = vol.Export
		server.Listen = vol.Listen
		server.TranAddr = vol.TranAddr
		server.Type = vol.Type
		server.MountDev = filepath.VolumeName(vol.Export)
		server.Workdir = server_conf.Workdir
		server.ClusterAddr = server_conf.ClusterAddr
		server.Passphrase = server_conf.ClusterPassphrase
		if err := server.Init(); err != nil {
			return err
		}
		servers = append(servers, server)
	}
	return nil
}
